var express = require('express')
    , consolidate = require('consolidate')
    , path = require('path')
    , mysql = require('mysql')
    , bodyParser = require('body-parser')
    , session = require('express-session')
    ;

var app = express();

app.use(session({
    name: 'current_admin',
    secret: 'cnjd-student-manage-system',
    rolling: true,
    cookie: {
        maxAge: 1000 * 60 * 30
    }
}));

// parse all
// app.use(bodyParser());

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
// app.use(bodyParser.json());

var pool = mysql.createPool({
    host: '127.0.0.1'
    , user: 'root'
    , password: 'root'
    , database: 'cnjd_student_manage_system'
});

app.set('views', path.resolve(__dirname, 'views'));
app.set('view engine', 'html');
app.engine('html', consolidate.swig);

// app.use(function (req, res, next) {
//     if (req.session.current_admin) {
//         if (req.path === '/' && !req.xhr && req.method.toLowerCase() === 'get') {
//             return res.redirect('/students');
//         } else if (req.path === '/login' && req.xhr && req.method.toLowerCase() === 'post') {
//             return res.json({ code: 1, msg: '登录成功', data: null });
//         } else {
//             return next();
//         }
//     } else {
//         if (req.path === '/' && !req.xhr && req.method.toLowerCase() === 'get') {
//             return next();
//         } else if (req.path === '/login' && req.xhr && req.method.toLowerCase() === 'post') {
//             return next();
//         } else {
//             return res.redirect('/');
//         }
//     }
// });

app.get('/', function (req, res, next) {
    if (req.session.current_admin) {
        res.redirect('/students');
    } else {
        res.render('login');
    }
});

app.post('/api/login', function (req, res, next) {
    var login_acco = req.body.login_acco;
    var login_password = req.body.login_password;
    if (login_acco && login_password) {
        // 查询数据库
        pool.query(
            'SELECT * FROM t_admin WHERE login_acco = ? AND login_password = ?',
            [login_acco, login_password],
            function (error, results, fields) {
                if (error) {
                    throw error;
                }
                if (results.length > 0) {
                    var admin = results[0];
                    req.session.current_admin = admin;
                    res.json({ code: 1, msg: '登录成功', data: { name: admin.name } });
                } else {
                    res.json({ code: -1, msg: '账号或密码错误', data: null });
                }
            }
        );
    } else {
        res.json({ code: -1, msg: '参数非法', data: null });
    }
});

app.get('/logout', function (req, res, next) {
    delete req.session.current_admin;
    res.redirect('/');
});

app.get('/students', function (req, res, next) {
    if (req.session.current_admin) {
        res.render('students');
    } else {
        res.redirect('/');
    }
});

app.post('/api/students', function (req, res, next) {
    pool.query('SELECT * FROM t_student', function (error, results, fields) {
        if (error) throw error;
        res.json({ code: 1, msg: '查询成功', data: results });
    });
});

app.get('/student/insert', function (req, res, next) {
    res.render('student_insert');
});

app.post('/api/student/insert', function (req, res, next) {
    pool.query('INSERT t_student(name, sex, age, no, class_name) VALUES(?, ?, ?, ?, ?)', [
        req.body.name,
        req.body.sex,
        req.body.age,
        req.body.no,
        req.body.class_name
    ], function (error, results, fields) {
        if (error) throw error;
        if (results.affectedRows === 1) {
            res.json({ code: 1, msg: '添加成功', data: null });
        } else {
            res.json({ code: -1, msg: '添加失败', data: null });
        }
    });
});

app.get('/student/update', function (req, res, next) {
    pool.query('SELECT * FROM t_student WHERE id = ?', [
        req.query.id
    ], function (error, results, fields) {
        if (error) throw error;
        res.render('student_update', { student: results[0] });
    });
});

app.post('/api/student/update', function (req, res, next) {
    pool.query('UPDATE t_student SET name = ?, sex = ?, age = ?, no = ?, class_name = ? WHERE id = ?', [
        req.body.name,
        req.body.sex,
        req.body.age,
        req.body.no,
        req.body.class_name,
        req.body.id
    ], function (error, results, fields) {
        if (error) throw error;
        if (results.affectedRows === 1) {
            res.json({ code: 1, msg: '修改成功', data: null });
        } else {
            res.json({ code: -1, msg: '修改失败', data: null });
        }
    });
});

app.post('/api/student/delete', function (req, res, next) {
    var id = req.body.id;
    if (id) {
        pool.query('DELETE FROM t_student WHERE id = ?', [id], function (error, results, fields) {
            if (error) throw error;
            if (results.affectedRows === 1) {
                res.json({ code: 1, msg: '删除成功', data: null });
            } else {
                res.json({ code: -1, msg: '删除失败', data: null });
            }
        });
    } else {
        res.json({ code: -1, msg: '参数非法', data: null });
    }
});

(function (port, hostname) {

    app.listen(port, hostname, function () {
        console.log('app listening at http://%s:%s', hostname, port);
    });

})(8080, 'localhost');
